package com.lizonghui.googleplay.fragment;

import android.os.SystemClock;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.lizonghui.googleplay.base.BaseFragment;
import com.lizonghui.googleplay.base.BaseHolder;
import com.lizonghui.googleplay.base.LoadingPager;
import com.lizonghui.googleplay.base.SuperBaseAdapter;
import com.lizonghui.googleplay.bean.SubjectInfoBean;
import com.lizonghui.googleplay.control.SubjectHolder;
import com.lizonghui.googleplay.factory.ListViewFactory;
import com.lizonghui.googleplay.protocol.SubjectProtocol;

import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2016/6/16.
 */
public class SubjectFragment extends BaseFragment {


    private List<SubjectInfoBean> mSubjectInfoBeans;
    private SubjectProtocol mSubjectProtocol;

    @Override
    public View initSuccessView() {
        ListView listView = ListViewFactory.createListView();
        listView.setAdapter(new SubjectAdapter(listView, mSubjectInfoBeans));
        return listView;
    }

    //这里类型是适配类型，就是每一个项Item的类型SubjectInfoBean。协议请求的返回类是List<SubjectInfoBean>
    class SubjectAdapter extends SuperBaseAdapter<SubjectInfoBean> {
        //我们在SuperBaseAdapter中写入了是否加载更多的逻辑，如果后台有数据，我们就复写两个方法
        public SubjectAdapter(AbsListView absListView, List datas) {
            super(absListView, datas);
        }

        @Override
        public BaseHolder getSpecialHolder(int position) {
            return new SubjectHolder();
        }

        //是否有更多，从后台知道有。
        @Override
        protected boolean hasLoadMore() {
            return false;
        }

        //开始初始化加载更多
        @Override
        public List<SubjectInfoBean> initLoadMoreData() throws Exception {
            return mSubjectProtocol.loadData(mSubjectInfoBeans.size());


        }
    }

    @Override
    public LoadingPager.LoadedResultState initData() {
        SystemClock.sleep(2000);// 模拟网络耗时2s种

        //要从网络加载数据，就需要用协议请求，就要有protocol请求对象
        mSubjectProtocol = new SubjectProtocol();
        try {
            //得到protocol请求对象，就要去请求数据
            mSubjectInfoBeans = mSubjectProtocol.loadData(0);
            //得到数据之后就是校验数据
            return checkResData(mSubjectInfoBeans);
        } catch (IOException e) {
            e.printStackTrace();
            return LoadingPager.LoadedResultState.ERROR;
        }
    }


}